#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include <QThread>
#include <QtSql>

struct ServerInformation {
    QString adres;
    int port;
    QString name;
    QString username;
    QString password;
};

typedef QList<ServerInformation *> ServerInformationList;
Q_DECLARE_METATYPE(ServerInformationList)

class DatabaseManager : public QThread
{
Q_OBJECT
public:
    enum DatabaseManagerStateFlag {
        Idle = 0,
        DatabaseExists = 1,
        CreateDatabase = 2,
        GetServerList = 3,
        AddServer = 4,
        RemoveServer = 5
    };
    Q_DECLARE_FLAGS(DatabaseManagerState, DatabaseManagerStateFlag)

    explicit DatabaseManager(QObject *parent = 0);
    virtual ~DatabaseManager();

    static DatabaseManager *instance();

    void checkDatabaseExists();
    void createDatabase();
    void getServerList();
    void addServer(ServerInformation *serverInformation);
    void removeServer(ServerInformation *serverInformation);

    // State
    inline DatabaseManagerState databaseManagerState() const { return state; }

protected:
    void run();

signals:
    void databaseExists(bool exists);
    void serverList(ServerInformationList);
    void serverListChanged();

private slots:
    void wakeUp();

private:
    QSqlDatabase database;

    DatabaseManagerState state;

    bool quit;
    bool wokeUp;

    bool dbExists;

    ServerInformation *temporaryServerInformation;

    mutable QMutex mutex;
    mutable QWaitCondition cond;
};

#endif // DATABASEMANAGER_H
